/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   14-7-29 下午2:42 Created by dwzhang
 */
package com.jade.framework.base.comm.netty;

import java.util.List;

import com.jade.framework.base.comm.CommEndpoint;
import com.jade.framework.base.comm.MessageCodec;
import com.jade.framework.base.comm.ProtocolSession;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * 采用ByteBuf作为MessageCodec的输入，对Netty有一定的依赖。
 *
 * @author dwzhang
 * @version 1.0 14-7-29 下午2:42
 */
public class NettyMessageDecoder extends ByteToMessageDecoder
{
    protected CommEndpoint<Channel> endpoint;

    public NettyMessageDecoder(CommEndpoint<Channel> endpoint)
    {
        this.endpoint = endpoint;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> objects)
            throws Exception
    {
        ProtocolSession session = endpoint.getSession(ctx.channel());
        MessageCodec<ByteBuf, ByteBuf> codec = session.getProtocol().getMessageCodec();
        do {
            int saveReaderIndex = byteBuf.readerIndex();
            Object result = codec.decode(session, byteBuf);
            if (result != MessageCodec.DecodeResult.NEED_MORE_INPUT) {
                session.getProtocol().getLog().trace("Receive a message:" + result);
                objects.add(result);
            }
            else {
                byteBuf.readerIndex(saveReaderIndex);
                break;
            }
        }
        while (byteBuf.isReadable());
    }
}
